import React from 'react'
import {
  Upload, message, Button, Icon
} from 'antd'
import {FormattedMessage} from 'react-intl'

const ImportBasicQuizModal = ({type, refreshQuizzes}) => {
  const getHeaderFromLocalStorage = (key) => window.localStorage.getItem(key)
  const checkFileFormat = file => {
    if (type === 'excel') {
      return file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
    }
    return file.name.endsWith('.zip')
  }
  const action = `./api/v3/basicQuizzes/${type}`

  const props = {
    name: 'file',
    action,
    headers: {
      token: getHeaderFromLocalStorage('jwt'),
      sessionId: getHeaderFromLocalStorage('sessionId')
    },
    beforeUpload (file) {
      if (checkFileFormat(file)) {
        return true
      }
      message.error('error format')
      return false
    },
    onChange (info) {
      if (info.file.status === 'done') {
        message.success(`Quiz imported successfully.`)
        refreshQuizzes()
      } else if (info.file.status === 'error') {
        message.error(info.file.response.message)
      }
    }
  }
  return <div>
    <Upload {...props}>
      <Button>
        <Icon type='upload' />
        {type }<FormattedMessage id='导入' />
      </Button>
    </Upload>
    <span style={{lineHeight: '30px'}}>
      <a target='_blank' href={
        type === 'excel'
          ? 'https://s3.cn-north-1.amazonaws.com.cn/quiz-center-files/import_basic_quiz_template.xlsx'
          : 'https://shimo.im/docs/1LNDGAw6TU8I0Guq'
      }>
        <FormattedMessage id='下载模版' />
      </a>
    </span>
  </div>
}

export default ImportBasicQuizModal
